<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="referrer" content="no-referrer">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分页数据表格展示</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
        .star {
            cursor: pointer;
            font-size: 20px;
            color: #333333;
        }
        .star.filled {
            color: gold;
        }
    </style>
</head>
<body>
<div class="container mt-5">
    <h1 class="d-flex justify-content-between align-items-center">
        分页数据表格展示
        <!--<div>
            <input type="text" id="uname" class="form-control me-2" placeholder="搜索...">
            <button id="searchButton" class="btn btn-primary" onclick="fetchData()">搜索</button>
        </div>-->
        <div class="top-right-link">
            <a href="./myCollectBooks.html" target="_blank">我的收藏</a>
        </div>
    </h1>
    <table class="table table-striped">
        <thead>
        <tr>
            <th style="width:300px;">书名</th>
            <th>isbn</th>
            <th>评分</th>
            <th>人数</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="data-table-body"></tbody>
    </table>

    <nav aria-label="Page navigation">
        <ul class="pagination justify-content-center mt-3" id="pagination"></ul>
    </nav>
</div>

<script>
    const rowsPerPage = 10;
    let currentPage = 1;
    let favorites = new Set();

    $(function (){
        fetchData(currentPage);
    });

    function fetchData() {

        var apiUrl = '/borrowBooksPage';
        const quesyString = window.location.search;
        const queryParams = new URLSearchParams(quesyString);
        const type = queryParams.get("type");
        if(null!=type){
            apiUrl += "?classify="+type;
        }
        $.ajax({
            url: apiUrl,
            method: 'GET',
            data: {
                begin: rowsPerPage*(currentPage-1),
                offset: rowsPerPage
            },
            dataType: 'json',
            success: function(response) {
                data = response.data;
                renderTable(response.data,currentPage);
                renderPagination(response.total,currentPage,rowsPerPage);
            },
            error: function(xhr, status, error) {
                console.error('获取数据失败:', error);
            }
        });
    }

    function renderTable(data) {
        $('#data-table-body').empty();
        $.each(data, function(index, item) {
            let row = '<tr><td>' + item.bookName + '</td><td>' + item.isbn + '</td><td>' + item.rating + '</td><td>' + item.evaluateNum + '</td><td>';
            row += '<span title="aaa" id="' + item.isbn + '" class="star '+ (item.isCollect === 1? 'filled' : '') + '" onclick="toggleFavorite(\'' + item.isbn + '\',\'' + item.library + '\',' + item.isCollect + ')">&#9733;</span>';
            row += '</td></tr>';
            $('#data-table-body').append(row);
        });
    }

    function toggleFavorite(id,library,isCollect) {
        if(isCollect==0){
            collect(id, library, 1).then(res => {
                if (res === 1) {
                    // 更新 DOM 或执行其他操作
                    $("#"+id).addClass("filled");
                    $("#" + id).attr("onclick", "toggleFavorite('" + id + "','" + library + "',1)");
                    alert("收藏成功");
                    //window.location.reload();
                }
            }).catch(error => {
                console.error('收藏操作失败:', error);
                alert("收藏失败，请重试");
            });

        }else if(isCollect==1){
            collect(id, library, 0).then(res => {
                if (res === 1) {
                    // 更新 DOM 或执行其他操作
                    $("#"+id).removeClass("filled");
                    $("#" + id).attr("onclick", "toggleFavorite('" + id + "','" + library + "',0)");
                    alert("取消成功");
                    //window.location.reload();
                }
            }).catch(error => {
                console.error('收藏操作失败:', error);
                alert("取消失败，请重试");
            });
        }
    }

    function collect(isbn, library, isCollect) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: '/collect',
                method: 'GET',
                data: { isbn, library, isCollect },
                dataType: 'json',
                success: function(response) {
                    resolve(response);
                },
                error: function(xhr, status, error) {
                    reject(error);
                    console.error('获取数据失败:', error);
                }
            });
        });
    }
    function renderPagination(totalItems, currentPage, itemsPerPage) {
        $('#pagination').empty();
        var totalPages = Math.ceil(totalItems / itemsPerPage);

        var startPage = Math.max(currentPage - 4, 1);
        var endPage = Math.min(currentPage + 4, totalPages);

        if (currentPage > 1) {
            $('#pagination').append('<li class="page-item"><a class="page-link" href="" data-page="' + (currentPage - 1) + '">&laquo;</a></li>');
        }

        for (var i = startPage; i <= endPage; i++) {
            var activeClass = (i === currentPage) ? ' active' : '';
            $('#pagination').append('<li class="page-item' + activeClass + '"><a class="page-link" href="#" data-page="' + i + '">' + i + '</a></li>');
        }

        if (currentPage < totalPages) {
            $('#pagination').append('<li class="page-item"><a class="page-link" href="#" data-page="' + (currentPage + 1) + '">&raquo;</a></li>');
        }
    }

    $('#pagination').on('click', 'a', function(e) {
        e.preventDefault();
        var page = $(this).data('page');
        if (page) {
            currentPage = page;
            fetchData(currentPage);
        }
        //window.location.href="/canBorr2.html?page="+page+"&uname="+uname;
    });

</script>
</body>
</html>
